<template>
  <div v-show="visible" class="k-header-box">
    <!-- {{ id }} -->
    <div class="la yout-between"  id="view">
      <div class="" >
        <!-- {{ initData }} -->
        <!-- {{ topTaskYujingData }}
        {{ allTaskData }}
        {{ topTaskActive }} -->
        <el-tabs v-if="topTaskAllData" v-model="topTaskActive" @tab-click="stepsClickFn">
          <template v-for="(item, key) in initData.taskWitnessLinkAll">
            <el-tab-pane
              :name="item.value"
              v-if="topTaskAllData[item.value] && topTaskAllData[item.value].length"
              :key="key"
            >
              <span slot="label">
                {{ item.label }}({{ topTaskAllData[item.value].length }}个)
                <i
                  v-if="topTaskYujingData[item.value] && topTaskYujingData[item.value].isWarn"
                  class="icon-yujing2 font-danger"
                />
              </span>
            </el-tab-pane>
          </template>
        </el-tabs>
      </div>
      <div class="add-task-btn">
        <el-button
          v-if="addTaskShow && $hasBtnsPerm('BTN_ADD_WITNESS_SUB_TASK')"
          type="primary"
          plain
          size="mini"
          icon="el-icon-circle-plus-outline"
          @click="addTaskFn"
        >
          加入任务
        </el-button>
      </div>
    </div>
    <div class="top-box">
      <div ref="topTaskList-----" class="top-task-box">
        <!--  v-show="leftRightBtnFlag" -->
        <el-button
          :class="{ 'visible-hide': !leftRightBtnFlag }"
          type="text"
          size="default"
          icon="el-icon-arrow-left"
          @click="taskLeftFn"
        />
        <ul ref="refTaskList2" :class="{ 'task-list': true, topTaskVisible: !topTaskVisible }">
          <li
            v-for="(item, index) in topTaskData"
            :key="item.witnessSubTaskId"
            :class="[item.active]"
            @click="projectClickFn(item, index)"
            :id="'a' + item.witnessSubTaskId"
          >
            <div class="info">
              <!-- {{ item.witnessSubTaskId }} -->
              <div class="text1">
                <em>项目：</em>
                <span :title="item.projectName">{{ item.projectName }}</span>
              </div>
              <div v-if="item.bidSectionName" class="text2">
                <em>标段：</em>
                <span :title="item.bidSectionName">{{ item.bidSectionName }}</span>
              </div>
              <div v-if="item.projectBidSubTaskTime || item.projectBidSubTaskAddress" class="text3">
                <em>时间：</em>
                <span :title="TimeSettlement(item.projectBidSubTaskTime)">{{ TimeSettlement(item.projectBidSubTaskTime) }}</span>
                <em>标室：</em>
                <span :title="item.projectBidSubTaskAddress">{{ item.projectBidSubTaskAddress }}</span>
              </div>
            </div>
            <!-- && item.witnessSubTaskId != id) -->
            <div v-if="item.isWarn || item.danger" class="check">
              <i class="icon-yujing1" />
            </div>
            <!-- <div class="check"><i class="el-icon-check"></i></div> -->
          </li>
        </ul>
        <!--
          v-show="leftRightBtnFlag" -->
        <el-button
          :class="{ 'visible-hide': !leftRightBtnFlag }"
          type="text"
          size="default"
          icon="el-icon-arrow-right"
          @click="taskRightFn"
        />
      </div>
      <!-- <div class="ui-pt10">
          <el-button
            v-if="topTaskData.length"
            type="text"
            size="default"
            @click="topTaskVisible = !topTaskVisible"
            >{{ !topTaskVisible ? "收起" : "展开" }}
            <i
              :class="[
                topTaskVisible ? 'el-icon-arrow-down' : 'el-icon-arrow-up',
              ]"
            ></i>
          </el-button>
        </div> -->
    </div>
  </div>
</template>
<script>
  import { subtaskListPart } from "../api/api";
  import { mapMutations } from "vuex";
  import { GZAPI_EvaluationTime } from "../../gz_plugin/api";
  export default {
    components: {},
    props: {
      initData: {
        type: Object,
        default() {
          return {};
        }
      },
      addTaskShow: {
        type: Boolean,
        default: true
      },
      visible: {
        type: Boolean,
        default: false
      },
      taskActive: {
        type: String,
        default: ""
      },
      cid: {
        type: String,
        default: ""
      }
    },
    data() {
      return {
        leftRightBtnFlag: false,
        topTaskVisible: false,
        id: "",
        topTaskActive: "",
        topTaskAllData: {},
        topTaskData: [],
        currProjectData: {},
        topTaskYujingData: {}
      };
    },
    computed: {
      allTaskData() {
        return this.$store.getters.topTaskAllData;
      },
      yujingData() {
        return this.$store.getters.topTaskYujingData;
      },
      wsData() {
        return this.$websocket.getters.wsData;
      }
    },
    watch: {
      allTaskData: {
        handler(newVal) {
          // this.topTaskYujingData
          console.log("allTaskData", newVal);
          this.$set(this, "topTaskAllData", newVal);
        },
        immediate: true
      },
      yujingData: {
        handler(newVal) {
          // this.topTaskYujingData
          console.log("yujingData", newVal);
          this.$set(this, "topTaskYujingData", newVal);
        },
        immediate: true
      },
      wsData: {
        handler(newVal) {
          console.log("ws消息变化================", newVal);
          if (newVal) {
            console.log("newVal.witnessRecordList", newVal.witnessRecordList);
            console.log("this.id", this.id);
            // 全部信息、预警信息
            if (newVal.witnessInfoRecord) {
              // 管理员
              if (
                this.currProjectData.witnessSubTaskId === newVal.witnessInfoRecord.witnessSubTaskId &&
                newVal.witnessInfoRecord.witnessStatus === "EXCEPTION"
              ) {
                this.currProjectData.isWarn = true;
              }
              // 见证人员
              for (const key in this.topTaskAllData) {
                if (Object.hasOwnProperty.call(this.topTaskAllData, key)) {
                  const taskData = this.topTaskAllData[key];
                  console.log("taskData", key, taskData);
                  for (let i = 0; i < taskData.length; i++) {
                    const item = taskData[i];
                    if (
                      item.witnessSubTaskId === newVal.witnessInfoRecord.witnessSubTaskId &&
                      newVal.witnessInfoRecord.witnessStatus === "EXCEPTION"
                    ) {
                      // console.log("taskData",item.witnessSubTaskId ===
                      //   newVal.witnessInfoRecord.witnessSubTaskId);
                      // console.log("taskData",newVal.witnessInfoRecord.witnessStatus);
                      // console.log("3333333", i);
                      // console.log("3333333", key);
                      // let jylcType = taskData[i].jylcType;
                      // yujingData[key] ={isWarn:true} ;
                      // if (!this.topTaskYujingData[key].isWarn) {
                      //   }
                      this.$set(this.topTaskYujingData, key, { isWarn: true });
                      this.$set(this.topTaskAllData[key][i], "isWarn", true);
                      // this.$set(this.topTaskData[i], "isWarn", true);
                      break;
                    }
                  }
                }
              }
              console.log("3333333", this.topTaskYujingData);
              // this.topTaskYujingData =yujingData;
              // this.topTaskData.forEach((item, index) => {});
              // }
            }
            // if (newVal.witnessRecord) {
            //   console.log("newVal.witnessRecord", newVal.witnessRecord);
            // }
          }
        },
        immediate: true
      },
      topTaskData() {
        console.log("aaaaaaa");
        // 这里需要设计一下，dom渲染完在计算宽度 by link
        if (this.$refs.refTaskList2) {
          this.$nextTick(() => {
            this.leftRightBtnFlag =
              this.$refs.refTaskList2 && this.$refs.refTaskList2.scrollWidth > this.$refs.refTaskList2.clientWidth;
          });
        }
      },
      visible(val) {
        console.log("visible", val);
        if (val) {
          this.id = this.cid;
          console.log("initData", this.initData.taskWitnessLinkAll);
          // this.topTaskActive = this.taskActive;
          this.initFn();
        }
      }
    },
    beforeDestroy() {
      clearInterval(this.setIntervalFlg);
    },
    created() {
      this.initFn();
    },
    mounted() {
      this.scrollView();
    },
    methods: {
      //wei外部页签定位联动弹框页签可视区域
      scrollView(id) {
        if (id) {
          try {
            setTimeout(() => {
              document.getElementById("a" + id).scrollIntoView(true);
            }, 0);
            this.viewTop()
          } catch (error) {
            console.error(error);
          }
        } else {
          setTimeout(() => {
            document.getElementById("a" + this.$route.query.id).scrollIntoView(true);
          }, 0);
        }
      },
      nodeTab(tabName, tabId) {
        this.topTaskActive = tabName;
        this.changeAllTaskDataFn();
        this.scrollView(tabId);
        this.viewTop()
      },
      //----------------wei
      ...mapMutations(["GET_topTaskAllData"]),
      initFn() {
        // taskActive没有变化，需要重新赋值
        this.topTaskActive = this.taskActive;
        console.log("55555", this.topTaskActive);
        this.id = this.cid;
        console.log("this.id", this.id);
        console.log("this.$taskData.getters", this.$store.getters.topTaskAllData);
        this.topTaskAllData = this.allTaskData;
        // TODO 这里有联动，推送预警需要测试
        // this.topTaskAllData = JSON.parse(JSON.stringify(this.allTaskData));
        this.changeAllTaskDataFn();
        // this.subtaskListPartFn();
      },
      async changeAllTaskDataFn() {
        // let res = this.allTaskData;
        // this.initData.taskWitnessLinkAll.forEach((item) => {
        //   if (this.allTaskData[item.value]) {
        //     this.$set(this.topTaskAllData, item.value, this.allTaskData[item.value] || []);
        //     // this.$set(this.topTaskYujingData, item.value, []);
        //   }
        //   // this.topTaskYujingData[item.value] = [];
        // // });
        // console.log("allTaskData", this.allTaskData);
        // this.$set(this, "topTaskAllData", this.allTaskData);
        await this.topTaskAllDataFn(); // 添加 jylcType 属性
        this.topTaskData = this.topTaskAllData[this.topTaskActive];
        // 选中任务
        await this.checkRecordFn();
      },
      // 加入任务 回调用
      addTaskFn() {
        // this.addTaskVisible = true;
        this.$emit("addTaskFn");
      },
      taskLeftFn() {
        console.log("this.$refs.refTaskList2.scrollLeft", this.$refs.refTaskList2.scrollLeft);
        console.log("this.$refs.refTaskList2.scrollWidth", this.$refs.refTaskList2.scrollWidth);
        console.log("this.$refs.refTaskList2.clientWidth", this.$refs.refTaskList2.clientWidth);
        this.$refs.refTaskList2.scrollLeft -= 600;
      },
      taskRightFn() {
        console.log("this.$refs.refTaskList2.scrollLeft", this.$refs.refTaskList2.scrollLeft);
        this.$refs.refTaskList2.scrollLeft += 600;
      },
      async projectClickFn(data, i) {
        console.log("i", i);
        this.currProjectData = data;
        this.topTaskData.forEach((item, index) => {
          if (i === index) {
            // sessionStorage.setItem("witnessSubTaskId", item.witnessSubTaskId);
            this.id = item.witnessSubTaskId;
            this.$set(this.topTaskData[index], "active", "active");
          } else {
            this.$set(this.topTaskData[index], "active", "");
          }
        });

        this.$emit("selectedTaskFn", data);

        // 表单重置，放到checkRecordFn中
        await this.checkRecordFn(); // 选中
        // //新增事项
        // await this.witnessRecordListFn();
        // await this.infoRecordQuerylistFn();
        // await this.initFn();
        //wei子组件调用父组件方法
        const childObj = {
          child: this.id,
          name: "child"
        };
        this.$emit("fatherMethod", childObj);
        this.scrollView(this.id);
        //-----------wei
      },
      // 招投开评定切换
      async stepsClickFn() {
        this.currProjectData = {};
        const key = this.topTaskActive;
        console.log("key", key);
        if (this.topTaskAllData[key]) {
          // 选中任务
          this.topTaskData = JSON.parse(JSON.stringify(this.topTaskAllData[key]));
          if (this.topTaskData.length) {
            this.id = this.topTaskData[0].witnessSubTaskId;
            // 选中任务
            await this.checkRecordFn();
            // sessionStorage.setItem("witnessSubTaskId", this.id);
          } else {
            this.id = "";
            // sessionStorage.setItem("witnessSubTaskId", this.id);
          }
        }
        //wei子组件调用父组件方法

        let queryId = "";
        if (this.topTaskData.length) {
          this.topTaskData.forEach((item) => {
            if (item.active === "active") {
              queryId = item.witnessSubTaskId;
            }
          });
        }
        this.$emit("fatherNodeTab", this.topTaskActive, queryId);
        this.scrollView(queryId);
        //-----------wei
        // // 初始化 表单
        // this.initFromFn();
        // this.$emit("selectedTaskFn", this.topTaskData[0]);//
        // this.$emit("initFromFn", this.id);
        // this.$emit("setIdFn", this.id);
      },
      // 见证人员-任务列表 /gdw/witness/subtask/list
      async subtaskListPartFn() {
        this.topTaskData = [];
        // return
        try {
          const p = {
            pageSize: -1, // 每页条数
            witnessSubTaskStatus: "WITNESSING" // 见证状态
          };
          const res = await GZAPI_EvaluationTime.subtaskListPart(p);
          console.log("subtaskListPart", res);
          // console.log("this.initData.taskWitnessLinkAll", this.initData.taskWitnessLinkAll);
          if (res.success) {
            // 保持顺序,见证环节
            this.initData.taskWitnessLinkAll.forEach((item) => {
              if (res.data[item.value]) {
                this.$set(this.topTaskAllData, item.value, res.data[item.value] || []);
                // this.$set(this.topTaskYujingData, item.value, []);
              }
              // this.topTaskYujingData[item.value] = [];
            });
            await this.topTaskAllDataFn(); // 添加 jylcType 属性
            // this.topTaskKeys = Object.keys(this.topTaskAllData);
            // console.log("this.topTaskKeys", this.topTaskKeys);
            // await this.webSocketTaskFn(this.topTaskAllData["ZB"]);
            // await this.webSocketTaskFn(this.topTaskAllData["TB"]);
            // await this.webSocketTaskFn(this.topTaskAllData["KB"]);
            // await this.webSocketTaskFn(this.topTaskAllData["PB"]);
            // await this.webSocketTaskFn(this.topTaskAllData["DB"]);
            // this.topTaskData = res.data[this.topTaskKeys[0]];
            // this.topTaskData = this.topTaskAllData.ZB;
            this.topTaskData = this.topTaskAllData[this.topTaskActive];
            // if (!this.id && this.topTaskData.length) {
            //   this.id = this.topTaskData[0].witnessSubTaskId;
            //   // sessionStorage.setItem("witnessSubTaskId", this.id);
            // }
            // 选中任务
            await this.checkRecordFn();
          } else {
            this.$message({
              type: "error",
              message: "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      // 选中任务
      async checkRecordFn() {
        // console.log("ov", this.topTaskAllArr);
        // this.topTaskAllData[this.topTaskActive];
        // this.initFromFn();
        // this.$emit("initFromFn");
        console.log("id", this.id);
        const currTask = this.topTaskAllArr.filter((item) => item.witnessSubTaskId === this.id);
        console.log("ovcurrTask", currTask);
        console.log("ovtopTaskData", this.topTaskData);
        // let currF = this.topTaskData.some((item) => {
        //   return item.witnessSubTaskId === this.id;
        // });
        if (currTask.length === 0) {
          // this.id = this.topTaskAllData[this.topTaskActive].witnessSubTaskId;
          return;
        }
        if (this.$route.query.id !== this.id) {
          this.$router.replace({
            query: {
              id: this.id
              // type: this.id,
            }
          });
        }
        // this.topTaskActive = currTask[0].jylcType;
        this.topTaskData = this.topTaskAllData[this.topTaskActive];
        // let flag = "";
        let i = 0;
        this.topTaskData.forEach((item, index) => {
          if (this.id === item.witnessSubTaskId) {
            i = index;
            // this.$set(this.topTaskData[index], "active", "active");
          } else {
            this.$set(this.topTaskData[index], "active", "");
          }
        });
        console.log("sssss3", i);
        this.currProjectData = this.topTaskData[i] || {};
        // this.projectClickFn();
        this.$emit("selectedTaskFn", this.currProjectData);
        // id 没有找到走这里
        this.$set(this.topTaskData[i], "active", "active");
        // this.$set(this.topTaskData[i], "danger", "");
        // this.$set(this.topTaskData[i], "isWarn", false); //
        const { jylcType } = this.topTaskData[i];
        const flag = this.topTaskData.some((item) => item.isWarn);
        // if (condition) {
        // }
        this.$set(this.topTaskYujingData, jylcType, { isWarn: flag });
        // this.topTaskYujingData[jylcType].isWarn = flag;
        // 更新选项卡的灯泡
        // this.updateIsWarnFn();
        // this.$emit("updateIsWarnFn");
        this.id = this.topTaskData[i].witnessSubTaskId;
        // 侧边栏、和列表接口
        // await this.witnessRecordListFn();
        // await this.infoRecordQuerylistFn(); //
      },
      async topTaskAllDataFn() {
        const ok = Object.keys(this.topTaskAllData);
        const ov = Object.values(this.topTaskAllData);
        let arr = [];
        ok.forEach((item, index) => {
          ov[index].forEach((vitem) => {
            vitem.jylcType = item; // 改变源对象的属性
            if (vitem.isWarn) {
              this.$set(this.topTaskYujingData, item, { isWarn: true });
              // this.topTaskYujingData[item].isWarn = true;
            }
          });
          arr = arr.concat(ov[index]);
        });
        console.log("ov", ov);
        console.log("ov", arr);
        this.topTaskAllArr = arr;
      },
      //截取页签时间
      TimeSettlement(time){
          const T = time.replace(/\-/g,"").slice(0,14)
          return  T
      },
      //切换页签数据置顶
      viewTop(){
         setTimeout(() => {
          document.getElementById("view").scrollIntoView(true);
        },0);
      },
    }
  };
</script>
<style lang="scss" scoped>
  .top-box {
    width: 100%;
    height: 50px;
    z-index: 9;
    position: relative;
    border-bottom: 1px solid $line;
    display: flex;
    align-items: center;
    flex-flow: row nowrap;
    justify-content: space-between;
    flex-direction: row;
    // h2 {
    //   font-size: 14px;
    //   line-height: 24px;
    //   margin-right: 8px;
    //   display: flex;
    //   .task-status {
    //     margin-left: 4px;
    //   }
    //   span {
    //     vertical-align: middle;
    //   }
    //   .project-title {
    //     flex: 1;
    //     display: inline-block;
    //     overflow: hidden; //超出的文本隐藏
    //     text-overflow: ellipsis; //溢出用省略号显示
    //     white-space: nowrap; //溢出不换行
    //     .short-title {
    //       width: 100%;
    //       max-width: 40em;
    //       display: inline-block;
    //       overflow: hidden; //超出的文本隐藏
    //       text-overflow: ellipsis; //溢出用省略号显示
    //       white-space: nowrap; //溢出不换行
    //     }
    //   }
    // }
    .top-btns {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    // 任务列表
    .top-task-box {
      position: absolute;
      bottom: -53px;
      width: 100%;
      left: 0;
      display: flex;
      align-items: center;
      background: #fff;
      box-shadow: 0px 3px 10px rgba($color: #000000, $alpha: 0.4);
      .visible-hide {
        visibility: hidden;
      }
      ul.task-list {
        height: 83px;
        margin-right: 10px;
        overflow: auto;
        display: flex;
        flex: 1;
        li {
          width: 325px;
          margin-right: 10px;
          padding: 0 12px;
          display: flex;
          align-items: center;
          position: relative;
          cursor: pointer;
          // justify-content: center;
          .check {
            // display: none;
            position: absolute;
            top: 0;
            right: 0px;
            width: 22px;
            height: 22px;
            color: #fff;
            &::before {
              position: absolute;
              top: 0;
              right: 0;
              content: "";
              height: 0;
              width: 0;
              overflow: hidden;
              font-size: 0;
              line-height: 0;
              border-top: 22px solid #1890ff;
              border-left: 22px solid transparent;
            }
            i {
              position: absolute;
              top: 1px;
              right: 2px;
              width: 10px;
              font-size: 10px;
              transform: scale(0.8);
            }
          }
          &.active {
            // background: #dbedff;
            background: #1890ff;
            color: #fff;
            .check {
              display: block;
            }
            &:hover {
              background: #1890ff;
              color: #fff;
            }
          }
          // &.active:hover {
          //   background: #dbedff;
          //   color: #555;
          // }
          &:hover {
            background: #f7fbff;
            color: #1890ff;
          }
          .task-status {
            // text-align: center;
            width: 24px;
            height: 24px;
            display: inline-block;
            position: relative;
            i {
              display: none;
            }
            i.danger {
              display: block;
              border-radius: 50%;
              position: absolute;
              top: 0;
              left: 0;
              width: 22px;
              height: 22px;
              border: 1px solid #ff4b53;
              em {
                color: #ff4b53;
                position: absolute;
                width: 11px;
                height: 11px;
                border: none;
                background: #fff;
                font-size: 10px;
                border-radius: 50%;
                right: -6px;
                bottom: 0px;
              }
            }
          }
          .info {
            flex: 1;
            padding-left: 8px;
            padding-right: 5px;
            line-height: 18px;
            padding: 4px;
            width: 325px;
            .text1,
            .text2 {
              width: 325px;
              display: inline-block;
              em {
                font-style: normal;
                vertical-align: middle;
                display: inline-block;
              }
              span {
                width: 275px;
                vertical-align: middle;
                display: inline-block;
                overflow: hidden; //超出的文本隐藏
                text-overflow: ellipsis; //溢出用省略号显示
                white-space: nowrap; //溢出不换行
              }
            }
            .text3 {
              width: 325px;
              display: inline-block;
              em {
                font-style: normal;
                vertical-align: middle;
                display: inline-block;
              }
              span {
                padding-right: 10px;
                width: 110px;
                vertical-align: middle;
                display: inline-block;
                overflow: hidden; //超出的文本隐藏
                text-overflow: ellipsis; //溢出用省略号显示
                white-space: nowrap; //溢出不换行
              }
            }
          }
        }
      }
    }
  }
  .k-header-box {
    // height: 109px;
    position: relative;
    .add-task-btn {
      position: absolute;
      right: 0;
      top: 0;
    }
    .top-box {
      margin-top: 0px;
      height: auto;
      // position: absolute;
      align-items: flex-start;
      background: #fff;
      .top-task-box {
        // background: #b1c0d1;
        // .el-button {
        //   display: none;
        // }
        position: static;
        box-shadow: none;
      }
    }
    // .top-box .top-task-box ul.task-list.topTaskVisible {
    //   height: auto;
    //   overflow-y: auto;
    // }
    .top-box .top-task-box ul.task-list {
      // height: auto;
      // min-height: 57px;
      // max-height: 300px;
      // flex-wrap: wrap;
      // overflow: hidden;
      li {
        margin-top: 4px;
        // margin-bottom: 8px;
        max-height: 62px;
        padding: 4px 8px;
        border: 1px solid $line;
        border-radius: 4px;
      }
    }
    // .top-box .top-task-box ul.task-list li.active {
    //   background: none;
    //   border: 1px solid $primary;
    //   color: $primary;
    // }
    // .top-box .top-task-box ul.task-list li.active:hover{
    // }
    .top-box .top-task-box ul.task-list li .check::before {
      // background: #f00;
      border-top: 22px solid #f00;
      color: #fff;
      font-size: 14px;
    }
    .top-box .top-task-box ul.task-list li .check i {
      top: 0;
      right: 3px;
      font-size: 16px;
    }
  }
</style>
